package com.cqq.pro.upload;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqq.attachment.service.AttachmentService;
import com.cqq.attachment.service.bean.AttachmentBean;
import com.cqq.attachment.service.exception.AttachmentException;
import com.cqq.base.filter.FMContext;
import com.cqq.common.core.base.BaseController;
import com.cqq.common.core.bean.MessageBean;
import com.cqq.common.core.util.GuidUtil;
import com.cqq.pro.util.DownOrUpLoadUtil;
import com.cqq.pro.util.PropertiesUtil;

@Controller
@RequestMapping("/attachmentUpload")
public class AttachmentUploadController extends BaseController{

	public static final String FILE_PATH = PropertiesUtil.getConfigValue("file_path");
	
	@Autowired
	private AttachmentService attachmentService;
	
	@RequestMapping(value = { "uploadAttachment" })
	@ResponseBody
    public MessageBean uploadAttachment(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        log.info("in upload........begin.......");
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        List fileList = null;
        try {
                fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
        	log.error(ex.getMessage(), ex);
            return buildMessage(MESSAGE_TYPE_ERROR, "上传失败【接收附件】");
        }
        Integer fileType=0;
        if(request.getParameter("fileType")!=null)
        	fileType = Integer.parseInt(request.getParameter("fileType"));
        
        Iterator<FileItem> it = fileList.iterator();
        List<AttachmentBean> listBean = new ArrayList<AttachmentBean>();
        String dir = formate.format(new Date());
        while (it.hasNext()) {
                FileItem item = it.next();
                if (!item.isFormField()) {
                        String name = item.getName();
                        if (name == null || name.trim().equals("")) {
                                continue;
                        }
                        try {
                        	    log.info("in upload........begin to save picture......."+FILE_PATH);
                        	    AttachmentBean bean = new AttachmentBean();
                        	    String originfileName = item.getName();
                                String fileName = GuidUtil.generate()+originfileName.substring(originfileName.lastIndexOf('.'));
                                DownOrUpLoadUtil.saveFile(FILE_PATH+dir+"/", fileName, item);
                                
                                bean.setOriginFileName(originfileName);
                                bean.setFileName(fileName);
                                bean.setFileSize(item.getSize());
                                bean.setFilePath(dir);
                                bean.setFileType(fileType);
                                listBean.add(bean);
                                log.info("in upload........begin to save picture.......");
                        } catch (Exception e) {
                        	log.error(e.getMessage(), e);
                            return buildMessage(MESSAGE_TYPE_ERROR, "上传附件失败【保存附件】");
                        }
                }
        }
        
        //保存附件至数据库
        try {
			saveAttachMents(listBean);
		} catch (AttachmentException e) {
			log.error(e.getMessage(), e);
			return buildMessage(MESSAGE_TYPE_ERROR, "保存附件失败【保存附件】");
		}
        return buildMessage(MESSAGE_TYPE_SUCCESS,FILE_PATH, "上传成功",listBean);
    }
	
	
	@RequestMapping(value = { "uploadBigAttachment" })
	@ResponseBody
    public MessageBean uploadBidAttachment(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        log.info("in upload........begin.......");
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        List fileList = null;
        try {
                fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
        	log.error(ex.getMessage(), ex);
            return buildMessage(MESSAGE_TYPE_ERROR, "上传失败【接收附件】");
        }
        Integer fileType=0;
        if(request.getParameter("fileType")!=null)
        	fileType = Integer.parseInt(request.getParameter("fileType"));
        
        Iterator<FileItem> it = fileList.iterator();
        List<AttachmentBean> listBean = new ArrayList<AttachmentBean>();
        String dir = formate.format(new Date());
        while (it.hasNext()) {
                FileItem item = it.next();
                if (!item.isFormField()) {
                        String name = item.getName();
                        if (name == null || name.trim().equals("")) {
                                continue;
                        }
                        try {
                        	    log.info("in upload........begin to save picture......."+FILE_PATH);
                        	    AttachmentBean bean = new AttachmentBean();
                        	    String originfileName = item.getName();
                                String fileName = GuidUtil.generate()+originfileName.substring(originfileName.lastIndexOf('.'));
                                DownOrUpLoadUtil.saveBigFile(item.getInputStream(),FILE_PATH+dir+"/",fileName);
                                
                                bean.setOriginFileName(originfileName);
                                bean.setFileName(fileName);
                                bean.setFileSize(item.getSize());
                                bean.setFilePath(dir);
                                bean.setFileType(fileType);
                                listBean.add(bean);
                                log.info("in upload........begin to save picture.......");
                        } catch (Exception e) {
                        	log.error(e.getMessage(), e);
                            return buildMessage(MESSAGE_TYPE_ERROR, "上传附件失败【保存附件】");
                        }
                }
        }
        
        //保存附件至数据库
        try {
			saveAttachMents(listBean);
		} catch (AttachmentException e) {
			log.error(e.getMessage(), e);
			return buildMessage(MESSAGE_TYPE_ERROR, "保存附件失败【保存附件】");
		}
        return buildMessage(MESSAGE_TYPE_SUCCESS,FILE_PATH, "上传成功",listBean);
    }
	
	
	private static SimpleDateFormat formate = new SimpleDateFormat("yyyyMMdd");
	private void saveAttachMents(List<AttachmentBean> listBean) throws AttachmentException{
		if(listBean!=null&&listBean.size()>0){
			
			for (AttachmentBean bean : listBean) {
			    bean.setUserId(FMContext.getLoginUser().getId());
				bean.setId(attachmentService.insertSelective(bean));
			}
		}
	}
	
	@RequestMapping(value = { "deleteAttachment" })
	@ResponseBody
    public MessageBean deleteAttachment(Integer id) {
		if(id==null)
			return buildMessage(MESSAGE_TYPE_ERROR, "参数不能为空【删除附件】");
		try {
			AttachmentBean bean = attachmentService.selectByPrimaryKey(id);
			String filePath=FILE_PATH+bean.getFilePath()+"/"+bean.getFileName();
			DownOrUpLoadUtil.deleteFile(filePath);
			attachmentService.deleteByPrimaryKey(id);
			return buildMessage(MESSAGE_TYPE_SUCCESS,"删除附件成功");
		} catch (AttachmentException e) {
			log.error(e.getMessage(), e);
			return buildMessage(MESSAGE_TYPE_ERROR, "删除附件失败");
		}
		
	}
	
	
	@RequestMapping(value = { "uploadTest" })
	@ResponseBody
	public MessageBean uploadTest(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException ex) {
			ex.printStackTrace();
		}
		log.info("in upload........begin.......");
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("UTF-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			log.error(ex.getMessage(), ex);
			return buildMessage(MESSAGE_TYPE_ERROR, "上传失败【接收附件】");
		}
		
		Iterator<FileItem> it = fileList.iterator();
		List<AttachmentBean> listBean = new ArrayList<AttachmentBean>();
		String dir = formate.format(new Date());
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				String name = item.getName();
				if (name == null || name.trim().equals("")) {
					continue;
				}
				try {
					log.info("in upload........begin to save picture......."+FILE_PATH);
					AttachmentBean bean = new AttachmentBean();
					String originfileName = item.getName();
					String fileName = GuidUtil.generate()+originfileName.substring(originfileName.lastIndexOf('.'));
					DownOrUpLoadUtil.saveFile(FILE_PATH+dir+"/", fileName, item);
					
					bean.setOriginFileName(originfileName);
					bean.setFileName(fileName);
					bean.setFileSize(item.getSize());
					bean.setFilePath(dir);
					listBean.add(bean);
					log.info("in upload........begin to save picture.......");
				} catch (Exception e) {
					log.error(e.getMessage(), e);
					return buildMessage(MESSAGE_TYPE_ERROR, "上传附件失败【保存附件】");
				}
			}
		}
		
		//保存附件至数据库
		/*try {
			saveAttachMents(listBean);
		} catch (AttachmentException e) {
			log.error(e.getMessage(), e);
			return buildMessage(MESSAGE_TYPE_ERROR, "保存附件失败【保存附件】");
		}*/
		return buildMessage(MESSAGE_TYPE_SUCCESS,FILE_PATH, "上传成功",listBean);
	}
	

	
}
